#coding:utf-8
import os
import sys
import cv2 as cv
from enum import Enum
import pickle
import time
import numpy as np

class camera(Enum):#使用枚举类
    Default = 0
    HD_webcam_jetson = 0
    HD_webcam_PC = 1

device = camera.HD_webcam_PC.value
#cap = cv.VideoCapture(camera.Default.value)
cap = cv.VideoCapture(device)
flag = cap.isOpened()
workpath = os.getcwd()
t = time.localtime()

image_record = dict(time = [t.tm_hour,t.tm_min,t.tm_sec],\
                    date = [t.tm_year,t.tm_mon,t.tm_mday],
                    device = "HD Webcam",
                    palce = "none")#获取当地地点

def save_image_index():
    datapath = os.path.join(workpath,'data')
    f = open(os.path.join(datapath,'data.txt'),'a+')
    pickle.dump()

def save_camera_image(filename = "default",format = ".png",filepath = workpath):
    filepath = os.path.join(filepath,'image')
    if filename == "default":
        filename = str(image_record.get('date')[0]) + \
            '-'+\
            str(image_record.get('date')[1]) + \
            '-'+\
            str(image_record.get('time')[0]) + \
            '-'+\
            str(image_record.get('time')[1])

    if (flag):
        ret, frame = cap.read()
        frame = cv.flip(frame,1)
        #print(np.size(frame,0))
        #print(np.size(frame,1))
        frame = frame.astype(np.uint8)
        #print(np.size(frame,0))
        #print(np.size(frame,1))
        #time.sleep(0.1)
        #cv.imshow('test',frame)
        cv.imwrite(str(os.path.join(filepath,(filename + format))), frame)
        #print(os.path.join(filepath, (filename + format)))

        return 1
    else:
        print("failed open")
        return -1

def show_image(frame):
    cv.imshow("1",frame)

def get_image():
    cap = cv.VideoCapture(device)
    frame = cap.read()
    return frame

def test_camera():
    capture = cv.VideoCapture(1)
    while True:
        ret, frame = capture.read()
        #frame = cv.flip(frame,1)   #镜像操作
        cv.imshow("video", frame)
        key = cv.waitKey(50)
        #print(key)
        if key  == ord('q'):  #判断是哪一个键按下
            break
    cv.destroyAllWindows()


if __name__ == "__main__":
    for i in range(1,10):
        save_camera_image()
        time.sleep(1)
    #test_camera()